<?php

namespace aszx0413\yii2gii\models;

use Yii;

/**
 * This is the base model class.
 *
 * @property int    $id
 * @property string $created_at
 * @property string $updated_at
 * @property int    $status
 */
class AR extends \yii\db\ActiveRecord
{
	/**
	 * 默认 status 枚举
	 */
	const STATUS = [
		'0' => '无效',
		'1' => '正常',
		'9' => '待审',
	];

	/**
	 * beforeSave
	 * @param bool $insert
	 * @return bool
	 */
	public function beforeSave($insert)
	{
		if (!parent::beforeSave($insert)) {
			return false;
		}

		if ($this->isNewRecord) {
			// 新增记录
			$this->created_at = $this->created_at ?? date('Y-m-d H:i:s');
			$this->updated_at = '0000-00-00 00:00:00';
			$this->status     = $this->status ?? 1;
		} else {
			// 更新记录
			$this->updated_at = date('Y-m-d H:i:s');
		}

		return true;
	}

	/**
	 * @param $condition
	 * @return static
	 */
	public static function findOrNew($condition): self
	{
		$self = self::findOne($condition);
		if (!$self) {
			$self = new static();
			$self->setAttributes($condition);
		}

		return $self;
	}

	public function load($data, $formName = null)
	{
		$this->setAttributes($data, false);

		return true;
	}

	public function setAttributes($values, $safeOnly = false)
	{
		parent::setAttributes($values, $safeOnly);
	}

	public function getStatusHtml()
	{
		$status = $this->status;

		$styles = [
			'0' => 'secondary',
			'1' => 'success',
			'2' => 'success',
			'3' => 'info',
			'4' => 'info',
			'5' => 'info',
			'6' => 'info',
			'7' => 'warning',
			'8' => 'success',
			'9' => 'danger',
		];

		if (defined('static::STATUS_STYLES')) {
			$styles = static::STATUS_STYLES + $styles;
		}

		return '<span class="badge badge-soft-' . $styles[$status] . ' badge-subtle-' . $styles[$status] . ' rounded-0 status" data-id="' . $this->id . '">' . static::STATUS[$status] . '</span>';
	}

	public function toText($col)
	{
		$colConst = strtoupper($col);

		$enums = constant("static::$colConst");

		$text = '';
		if (is_array($enums)) {
			if (is_string($enums[$this->{$col}])) {
				$text = $enums[$this->{$col}];
			} else {
				$text = $enums[$this->{$col}]['_t'];
			}
		}

		return $text;
	}

	public function getError()
	{
		$errors = $this->getFirstErrors();

		return current($errors);
	}

	public function setError($err)
	{
		$this->addError('error', $err);

		return false;
	}
}